package com.hailiao.beidou.message.ui.page.connect

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.d10ng.compose.ui.AppColor
import com.d10ng.compose.ui.AppText
import com.d10ng.compose.ui.PageTransitions
import com.d10ng.compose.ui.base.CellRow
import com.d10ng.compose.ui.base.CellTitle
import com.d10ng.compose.ui.feedback.PullRefreshIndicator
import com.d10ng.compose.ui.feedback.pullRefresh
import com.d10ng.compose.ui.feedback.rememberPullRefreshState
import com.d10ng.compose.ui.navigation.NavBar
import com.d10ng.compose.ui.show.Tag
import com.hailiao.beidou.message.R
import com.hailiao.beidou.message.utils.back
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph

/**
 * 蓝牙连接界面
 * @Author d10ng
 * @Date 2024/3/5 13:50
 */
@RootNavGraph
@Destination(style = PageTransitions::class)
@Composable
fun BLEConnectScreen(
    model: BLEConnectScreenViewModel = viewModel()
) {
    val isScanning by model.isScanningFlow.collectAsState()
    val devices by model.devicesFlow.collectAsState(listOf())
    BLEConnectScreenView(
        isScanning = isScanning,
        devices = devices,
        onRefresh = model::onRefresh,
        onClickDevice = model::onClickDevice
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BLEConnectScreenView(
    isScanning: Boolean = false,
    devices: List<BLEDeviceData> = listOf(),
    onRefresh: () -> Unit = {},
    onClickDevice: (BLEDeviceData) -> Unit = {}
) {
    val state = rememberPullRefreshState(refreshing = isScanning, onRefresh = onRefresh)
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColor.Neutral.bg)
            .navigationBarsPadding()
    ) {
        NavBar(
            title = "蓝牙终端连接",
            titleAlignment = Alignment.CenterStart,
            onClickBack = { back() },
            border = true
        )
        Box(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
        ) {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .defaultMinSize(minHeight = 200.dp)
                    .pullRefresh(state)
            ) {
                itemsIndexed(devices, { _, d -> d.address }) { idx, item ->
                    if (idx == 0 && item.isAdapted) {
                        CellTitle(title = "已适配设备")
                    } else if (item.isAdapted.not() && (idx == 0 || devices[idx -1].isAdapted)) {
                        CellTitle(title = "其他设备")
                    }
                    DeviceCell(value = item) { onClickDevice(item) }
                }
            }
            PullRefreshIndicator(
                refreshing = isScanning, state = state,
                modifier = Modifier
                    .align(Alignment.TopCenter)
            )
        }
    }
}

@Composable
private fun DeviceCell(
    value: BLEDeviceData,
    onClick: () -> Unit = {}
) {
    val iconId = remember(value) {
        value.type?.getIconID() ?: R.drawable.round_bluetooth_24
    }
    CellRow(
        modifier = Modifier
            .background(Color.White)
            .clickable { onClick() }
            .padding(horizontal = 19.dp),
        divider = true,
        dividerPaddingValues = PaddingValues(0.dp)
    ) {
        Image(
            painter = painterResource(id = iconId),
            contentDescription = value.name,
            modifier = Modifier
                .padding(vertical = 12.dp)
                .size(40.dp),
            contentScale = ContentScale.Inside
        )
        Text(
            text = value.name,
            style = AppText.Normal.Title.default,
            modifier = Modifier
                .padding(start = 16.dp)
                .fillMaxWidth()
                .weight(1f)
        )
        value.type?.let { type ->
            Tag(
                text = type.getProtoVersion().shortText,
                color = type.getProtoVersion().color,
            )
        }
    }
}

@Preview
@Composable
private fun BLEConnectScreenPreview() {
    BLEConnectScreenView()
}